<template>
  <a-modal
    :open="visible"
    title="消费历史"
    width="1200px"
    @cancel="handleCancel"
    :footer="null"
  >
    <div class="consumption-history">
      <!-- 筛选区域 -->
      <div class="filter-section">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item label="宠物">
              <a-select
                v-model:value="filters.petId"
                placeholder="全部"
                @change="filterRecords"
              >
                <a-select-option value="">全部</a-select-option>
                <a-select-option
                  v-for="pet in customer?.pets"
                  :key="pet.id"
                  :value="pet.id"
                >
                  {{ pet.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="日期">
              <a-range-picker
                v-model:value="filters.dateRange"
                @change="filterRecords"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="单号">
              <a-input
                v-model:value="filters.orderNumber"
                placeholder="请输入单号信息"
                @keyup.enter="filterRecords"
              >
                <template #suffix>
                  <a-button type="text" @click="filterRecords">🔍</a-button>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="操作">
              <a-button type="primary" @click="filterRecords">查询</a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </div>

      <!-- 消费记录表格 -->
      <div class="consumption-table">
        <a-table
          :columns="columns"
          :data-source="filteredRecords"
          :pagination="pagination"
          size="small"
          row-key="id"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'pet'">
              <span>{{ record.petName }}</span>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'discountedAmount'">
              <span class="amount"
                >¥{{ record.discountedAmount.toFixed(2) }}</span
              >
            </template>
            <template v-else-if="column.key === 'actualAmount'">
              <span class="amount">¥{{ record.actualAmount.toFixed(2) }}</span>
            </template>
          </template>
        </a-table>
      </div>

      <!-- 底部统计 -->
      <div class="bottom-section">
        <div class="left-section">
          <a-button @click="printRecords">打印</a-button>
        </div>
        <div class="right-section">
          <span class="total-consumption">
            消费总额: ¥{{ totalConsumption.toFixed(2) }}
          </span>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

interface Props {
  visible: boolean;
  customer?: any;
}

interface Emits {
  (e: 'update:visible',value: boolean): void
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 筛选条件
const filters = ref({
  petId: '',
  dateRange: [dayjs().subtract(1, 'month'), dayjs()],
  orderNumber: '',
});

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 消费记录数据
const consumptionRecords = ref([
  {
    id: '1',
    petName: '球球',
    petId: 'P000002',
    time: '2019-08-07 14:30:00',
    orderNumber: 'ORD20190807001',
    status: 'completed',
    discountedAmount: 150.0,
    actualAmount: 135.0,
    cashier: '张医生',
  },
  {
    id: '2',
    petName: '蛋蛋',
    petId: 'P000004',
    time: '2019-08-06 10:15:00',
    orderNumber: 'ORD20190806001',
    status: 'completed',
    discountedAmount: 200.0,
    actualAmount: 180.0,
    cashier: '李医生',
  },
  {
    id: '3',
    petName: '球球',
    petId: 'P000002',
    time: '2019-08-05 16:45:00',
    orderNumber: 'ORD20190805001',
    status: 'pending',
    discountedAmount: 80.0,
    actualAmount: 80.0,
    cashier: '王医生',
  },
]);

// 表格列定义
const columns = [
  {
    title: '宠物',
    dataIndex: 'pet',
    key: 'pet',
    width: 100,
  },
  {
    title: '时间',
    dataIndex: 'time',
    key: 'time',
    width: 150,
  },
  {
    title: '单号',
    dataIndex: 'orderNumber',
    key: 'orderNumber',
    width: 150,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '账单折后金额',
    dataIndex: 'discountedAmount',
    key: 'discountedAmount',
    width: 120,
  },
  {
    title: '实收金额',
    dataIndex: 'actualAmount',
    key: 'actualAmount',
    width: 120,
  },
  {
    title: '收银员',
    dataIndex: 'cashier',
    key: 'cashier',
    width: 100,
  },
];

// 计算属性
const filteredRecords = computed(() => {
  let records = consumptionRecords.value;

  // 按宠物筛选
  if (filters.value.petId) {
    records = records.filter((record) => record.petId === filters.value.petId);
  }

  // 按日期筛选
  if (filters.value.dateRange && filters.value.dateRange.length === 2) {
    const startDate = filters.value.dateRange[0];
    const endDate = filters.value.dateRange[1];
    records = records.filter((record) => {
      const recordDate = dayjs(record.time);
      return recordDate.isAfter(startDate) && recordDate.isBefore(endDate);
    });
  }

  // 按单号筛选
  if (filters.value.orderNumber) {
    records = records.filter((record) =>
      record.orderNumber
        .toLowerCase()
        .includes(filters.value.orderNumber.toLowerCase()),
    );
  }

  // 更新分页总数
  pagination.value.total = records.length;

  return records;
});

const totalConsumption = computed(() => {
  return filteredRecords.value.reduce(
    (total, record) => total + record.actualAmount,
    0,
  );
});

// 方法
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    completed: 'green',
    pending: 'orange',
    cancelled: 'red',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    completed: '已完成',
    pending: '待处理',
    cancelled: '已取消',
  };
  return textMap[status] || status;
};

const filterRecords = () => {
  // 筛选逻辑已在计算属性中实现
  message.info('筛选条件已更新');
};

const printRecords = () => {
  message.info('打印消费记录');
};

const handleCancel = () => {
  emit('update:visible', false);
  // 重置筛选条件
  filters.value = {
    petId: '',
    dateRange: [dayjs().subtract(1, 'month'), dayjs()],
    orderNumber: '',
  };
};

// 监听顾客变化，更新筛选选项
watch(
  () => props.customer,
  (customer) => {
    if (customer) {
      // 可以在这里加载该顾客的消费记录
      message.info(`加载顾客 ${customer.name} 的消费记录`);
    }
  },
);
</script>

<style scoped>
.consumption-history {
  max-height: 600px;
  overflow-y: auto;
}

.filter-section {
  padding: 16px;
  margin-bottom: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.consumption-table {
  margin-bottom: 16px;
}

.bottom-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;
  border-top: 1px solid #f0f0f0;
}

.total-consumption {
  font-size: 16px;
  font-weight: 600;
  color: #1890ff;
}

.amount {
  font-weight: 600;
  color: #52c41a;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background: #fafafa;
}

:deep(.ant-form-item) {
  margin-bottom: 0;
}
</style>
